import { request } from '@inbiz/utils';
import {message} from 'antd'

// 获取应用列表数据
type ITrees = {
  DisplayName: string;
  ParenId?: string;
  WebSiteID: string;
  Trees: ITrees[];
};
export async function getWebSiteIDList(WebSiteId: string): Promise<ITrees[]> {
  return request(`/inbiz/api/services/engines/v3/app/appList`).then((res) => {
    return res.map((item: { AppId: any }) => {
      return {
        ...item,
        WebSiteID: item.AppId,
      };
    });
  });
}

export type IIndexData = {
  IndexName: string;
  IndexCode: string;
  IndexDesc?: string;
  IndexType: number;
  Id: number;
};
// 获取当前应用下的索引库
export async function getIndexList(params: {
  WebSiteID: string;
  isOtherSite: boolean;
  pageIndex: number;
  pageSize: number;
  token: string;
  KeyWord: string;
}): Promise<{
  Code: number;
  Data: {
    Total: number;
    Items: IIndexData[];
    Msg: string;
  };
}> {
  return request(
    `/search/IndexManage/GetIndexList?WebSiteId=${params.WebSiteID}&pageIndex=${params.pageIndex}&pageSize=${params.pageSize}&token=${params.token}&sortDesc=false&KeyWord=${params.KeyWord}&isOtherSite=${params.isOtherSite}`,
  ).then((res: any) => {
    if (res?.Data?.Items) {
      res.Data.Items = res.Data.Items.map((item: IIndexData) => ({
        IndexName: item.IndexName,
        IndexCode: item.IndexCode,
        IndexDesc: item.IndexDesc,
        IndexType: item.IndexType,
        Id: item.Id,
      }));
    }
    return res;
  });
}

// 通过索引库名获取当前所有的字段名
export type IField = {
  Id: number;
  IndexFieldDesc?: string;
  IndexFieldName: string;
  notDelete?: boolean;
  IndexFieldType: string;
};
export async function getAllIndexFieldListByIndexName(indexName: string): Promise<{
  Code: number;
  Data: IField[];
}> {
  return request(`/search/IndexFieldManage/GetAllIndexFieldListByIndexName?indexName=${indexName}`);
}

export type ISystemGroup = {
  count: number;
  groupName: string;
  groupNum: string;
};
// 索引库的系统分类
export function getSystemType(IndexName: string): Promise<{
  Code: number;
  Data: ISystemGroup[];
  Msg: string;
}> {
  return request('/search/IndexSearch/GetSearchDataByIndexName', {
    method: 'POST',
    requestType: 'form',
    data: {
      IndexName: IndexName, // 索引库名称
    },
  });
}

// 索引库的系统分类
export type ISearchData = {
  Code: number;
  SearchTime: number;
  PageCount: number;
  Total: number;
  RawList: {
    HighlightList: object;
    RawData: {
      filename?: string;
      fileid?: string;
      foldername?: string;
      similary?: number;
    };
  }[];
  SectionList: {
    IsGroup: boolean;
    Key: string;
    Sort: number;
    IsWhether: boolean;
    Value: string;
    SectionGroupData:{
      Key: string;
      Value: string;
      sectionItemList: {
        Count: number;
        Key: string;
        Value: string;
      }[];
    }[];
    IsShowTitle: boolean;
    sectionItemList: {
      Count: number;
      Key: string;
      Value: string;
      isAll?: boolean
    }[];
  }[];
};

interface SearchDataObj {
  Order?: string;
  KeyWord?: string;
  PageIndex: number;
  PageSize: number;
  IndexName: string;
  IsSaveKeyWord?: number;
  OpenPerm?: boolean;
  Sort?: string;
  SearchWhere?: string;
  HighlightField?: string;
  ModuleName?: string;
  SearchFields?: string;
  ExcludesFields?: string;
  groupNum?: string;
  IsFuzzySearch?: boolean;
  Mark?: string;
}
export function getSearchData(data:SearchDataObj ): Promise<ISearchData> {
  if (data.Mark) {
    return getSimilarImagesAsync(data);
  }
  return request('/search/IndexSearch/GetSearchData', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    },
    data,
  }).then((data) => {
    if (!data) {
      return {};
    }
    return data;
  });
}
type IParams = Parameters<typeof getSearchData>[0] & { Mark: string };
export function getSimilarImagesAsync(data: IParams): Promise<ISearchData> {
  return request('/search/IndexSearch/GetSimilarImagesAsync', {
    method: 'POST',
    requestType: 'form',
    data,
  }).then((data) => {
    if (!data) {
      return {};
    }
    return data;
  });
}

// 相似搜索
export type ISynonymWord = {
  Representation: {
    WordOrNull: string;
  };
};
export function GetSynonymWord({
  KeyWord,
  size = 10,
}: {
  size?: number;
  KeyWord?: string;
}): Promise<ISynonymWord[]> {
  if (!KeyWord) {
    return Promise.resolve([]);
  }
  return request('/WebCore', {
    method: 'POST',
    requestType: 'form',
    data: {
      module: 'WebClient',
      fun: 'GetSynonymWord',
      keyword: KeyWord, // 这个参数传的是搜索入口搜索框的内容
      size,
    },
  }).then((res: { result: any }) => res.result);
}

// 索引库的系统分组【统一索引库】
export function getIndexSystemList(IndexId: string) {
  return request('/search/IndexGroupField/GetListByParentId', {
    method: 'POST',
    requestType: 'form',
    data: {
      ParentCode: 0,
      IndexId: IndexId, // 索引库的id
    },
  });
}

// 搜索
export async function GetFileFacetSearch(WebSiteId: string) {
  return request('WebCore', {
    method: 'POST',
    requestType: 'form',
    data: {
      module: 'WebClient',
      fun: 'GetFileFacetSearch',
      searchXml: '',
    },
  });
}

export async function UpdateTemplateFile(
  appID: string,
  file: File,
): Promise<{
  fileName: string;
  path: string;
}> {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('groupName', 'template');

  return request(`/inbiz/api/services/staticresource/v3/file/system/${appID}`, {
    method: 'POST',
    data: formData,
  });
}

export async function getSearchTextData (data:SearchDataObj) {
  const newData = {
    Mark: data.Mark, // mark值/或文件id
    Sort: data.Sort, // 排序字段 默认similary
    Order: data.Order, //排序方式  默认desc
    PageIndex: data.PageIndex, //页码 默认1
    PageSize: data.PageSize, //页面大小 默认20
    SearchWhere:data.SearchWhere, // 高级搜索条件
    IndexName: data.IndexName, // 索引库 file
  }
  return request(`/search/IndexSearch/GetSimilarTextsAsync`, {
    method: 'POST',
    requestType: 'form',
    data: newData,
  })
}